<?php
namespace app\admin\controller\system;
use app\admin\model\publicuse\AssetsHand;
use app\admin\model\publicuse\PublicUse;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use PhpOffice\PhpSpreadsheet\Calculation\Logical\Boolean;
use smartybuilder\libs\Quickbuilder;
use think\Request;

/**
 * @ControllerAnnotation(title="应用管理")
 * Class Myapp
 * @package app\admin\controller\system
 */
class Myapp extends AdminController
{
//    use \app\admin\traits\Curd;
    /**
     * @NodeAnotation(title="列表")
     */
    public function index(){
        if($this->request->isAjax()){
            $array = PublicUse::getdir(root_path().'addons'.DIRECTORY_SEPARATOR,['system']);
            $newdata = [];
            $datas = $this->request->param();
            $name = null;
            $assets = null;
            $install = null;
            if(isset($datas['filter'])&&$datas['filter']){
                $datas = json_decode(htmlspecialchars_decode($datas['filter']),true);
                if(isset($datas['name'])&&$datas['name']){
                    $name = $datas['name'];
                }else{
                    $name = null;
                }
                if(isset($datas['assets'])&&$datas['assets']){
                    $assets = $datas['assets'];
                }else{
                    $assets = null;
                }
                if(isset($datas['install'])){
                    if($datas['install']==1){
                        $install = 1;
                    }else{
                        $install = 0;
                    }
                }else{
                    $install = null;
                }
            }
            foreach ($array as $key=>$value){
                $da = root_path().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
                if(!is_file($da)){
                    continue;
                }

                $value = json_decode(file_get_contents($da),true);
                if(isset($value['rely_on'])&&$value['rely_on']){
                    $value['rely_on'] = implode(',',$value['rely_on']);
                }
                if(!empty($name)){
                    if(strpos($value['name'],$name)===false){
                        continue;
                    }
                }
                if(!empty($assets)){
                    if(strpos($value['assets'],$assets)===false){
                        continue;
                    }
                }
                if($install!==null){
                    if($value['install']!=$install){
                        continue;
                    }
                }
//                dump($value);die();
                $newdata[] = $value;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($newdata),
                'data'  => $newdata,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 添加插件
     */
    public function add(){
        $array = PublicUse::getdir(root_path().'addons'.DIRECTORY_SEPARATOR,['.svn','layout']);
        $data = $this->request->param();
        if(isset($data['author_name'])){
            $data['install'] = 0;
            if(!isset($data['rely_on'])){
                $data['rely_on'] = [];
            }else{
                $rely_on = [];
                foreach ($data['rely_on'] as $value){
                    $rely_on[] = $value;
                }
                $data['rely_on'] = $rely_on;
            }
            //创建配置文件
            $file_name = root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
            $file_dir = root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'config';
            $dir =  root_path().'addons';
            $data['table'] = [];
            $data['menu'] = [];
            $data['status'] = 1;
            $str = json_encode($data,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
            if(!is_file($file_name)){
                if(!is_dir($file_dir)){
                    chmod($dir,0777);
                    mkdir($file_dir,0777,true);
                }
                chmod($file_dir,0777);
                $bool = file_put_contents($file_name,$str);
            }else{
                chmod($file_dir,0777);
                $bool = file_put_contents($file_dir,$str);
            }
            if(!$bool){
                return $this->error('添加失败');
            }
            //插件配置文件
            $str = file_get_contents(root_path().'addons'.DIRECTORY_SEPARATOR.'Plugin.txt');
            $str = str_replace("{{NAME}}",$data['assets'],$str);
            $str = str_replace("{{NAMESPACE}}",$data['assets'],$str);
            $str = str_replace("{{TITLT}}",$data['name'],$str);
            $str = str_replace("{{DESCRIPTION}}",$data['description'],$str);
            $str = str_replace("{{AUTHOR}}",$data['author_name'],$str);
            file_put_contents(root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'Plugin.php',$str);
            $ob = new AssetsHand();
            $ob->moveFile(root_path().'addons'.DIRECTORY_SEPARATOR.'layout',root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.'layout');
            //创建sql文件夹
            $sql_path = root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'sql';
            if(!is_dir($sql_path)){
                chmod(root_path().'addons',0777);
                mkdir($sql_path,0777,true);
            }
            file_put_contents($sql_path.DIRECTORY_SEPARATOR.'sql.lock',time());
            return $this->success('添加成功');
        }else{
            return Quickbuilder::makeForm()
                ->setAction()
                ->set_up_form('input','插件名','name','')
                ->set_up_form('input','插件标识','assets','',[],'不可与其他的标识冲突')
                ->set_up_form('textarea','描述','description','')
                ->set_up_form('input','作者姓名','author_name','')
                ->set_up_form('input','作者手机','author_phone','')
                ->set_up_form('input','作者邮箱','author_email','')
                ->set_up_form('checkbox','插件','rely_on',[],$array,'',false)
                ->set_button('submit','提交')
                ->fetch();
        }
    }
    /**
     * 修改插件
     */
    public function edit(){
        $assets = $this->request->param('assets');
        $data = $this->request->param();
        $file_name = root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
        $file_dir = root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'config';
        $dir =  root_path().'addons';
        if(is_file($file_name)){
            $shuju = json_decode(file_get_contents($file_name),true);
        }else{
            $shuju = [];
        }
        if(isset($data['author_name'])){
            $shuju['name'] = $data['name']??'';
            $shuju['description'] = $data['description']??'';
            $shuju['author_name'] = $data['author_name']??'';
            $shuju['author_phone'] = $data['author_phone']??'';
            $shuju['author_email'] = $data['author_email']??'';
            if(!isset($data['rely_on'])){
                $data['rely_on'] = [];
            }else{
                $rely_on = [];
                foreach ($data['rely_on'] as $value){
                    $rely_on[] = $value;
                }
                $shuju['rely_on'] = $rely_on;
            }
            $str = json_encode($shuju,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
            if(!is_file($file_name)){
                if(!is_dir($file_dir)){
                    chmod($dir,0777);
                    mkdir($file_dir,0777,true);
                }
                chmod($file_dir,0777);
                $bool = file_put_contents($file_name,$str);
            }else{
                chmod($file_name,0777);
                $bool = file_put_contents($file_name,$str);
            }
            if(!$bool){
                return $this->error('修改失败');
            }
            $str = file_get_contents(root_path().'addons'.DIRECTORY_SEPARATOR.'Plugin.txt');
            $str = str_replace("{{NAME}}",$data['assets'],$str);
            $str = str_replace("{{NAMESPACE}}",$data['assets'],$str);
            $str = str_replace("{{TITLT}}",$data['name'],$str);
            $str = str_replace("{{DESCRIPTION}}",$data['description'],$str);
            $str = str_replace("{{AUTHOR}}",$data['author_name'],$str);
            file_put_contents(root_path().'addons'.DIRECTORY_SEPARATOR.$data['assets'].DIRECTORY_SEPARATOR.'Plugin.php',$str);
            return $this->success('修改成功');
        }else{
            $array = PublicUse::getdir(root_path().'addons'.DIRECTORY_SEPARATOR,[$assets,'.svn','layout']);
            return Quickbuilder::makeForm()
                ->setAction()
                ->set_up_form('input','插件名','name',$shuju['name']??'')
                ->set_up_form('textarea','描述','description',$shuju['description']??'')
                ->set_up_form('input','作者姓名','author_name',$shuju['author_name']??'')
                ->set_up_form('input','作者手机','author_phone',$shuju['author_phone']??'')
                ->set_up_form('input','作者邮箱','author_email',$shuju['author_email']??'')
                ->set_up_form('checkbox','插件','rely_on',$shuju['rely_on']??[],$array,'',false)
                ->set_button('submit','提交')
                ->fetch();
        }
    }
    public function install(){
        set_time_limit(0);
        ignore_user_abort(true);
        $assets = $this->request->param('assets');
        return $this->installs($assets);
//        $data = $this->request->param();
//        if(isset($data['mode'])){
//            if($data['mode']==1){
//                return $this->installs($assets);
//            }else{
//                return $this->notcoverinstall($assets);
//            }
//        }else{
//            return Quickbuilder::makeForm()
//                ->setAction()
//                ->set_up_form('none','','assets',$assets)
//                ->set_up_form('radio','安装方式','mode',1,[1=>'覆盖',2=>'不覆盖'])
//                ->set_button('submit','提交')
//                ->fetch();
//        }
    }
    protected function installs($assets){
        $dir = root_path().'addons'.DIRECTORY_SEPARATOR.$assets.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
        if(!is_file($dir)){
            return $this->error('插件不存在');
        }
        $shuju = json_decode(file_get_contents($dir),true);
        if(isset($shuju['rely_on'])&&!empty($shuju['rely_on'])){
            foreach ($shuju['rely_on'] as $value){
                $value_dir = root_path().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
                if(!is_file($value_dir)){
                    return $this->error('依赖模块不存在');
                }
                $value_shuju = json_decode(file_get_contents($value_dir),true);
                if(!(isset($value_shuju['install'])&&$value_shuju['install']==1)){
                    return $this->error("{$value}模块没有安装");
                }
            }
        }
        $obj = new AssetsHand();
        $bool = $obj->installAsset($assets,$shuju);
        if(!$bool){
            return $this->error($obj->getMessage());
        }
        $shuju['install'] = 1;
        chmod($dir,0777);
        $str = json_encode($shuju,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
        $bool = file_put_contents($dir,$str);
        if(!$bool){
            return $this->error('修改失败');
        }
        list($bool,$error) = AssetsHand::installConfig($assets);
        if(!$bool){
            return $this->error($error);
        }
        return $this->success('安装成功');
    }
    protected function notcoverinstall($assets){
        set_time_limit(0);
        ignore_user_abort(true);
//        $assets = $this->request->param('assets');
        $dir = root_path().'addons'.DIRECTORY_SEPARATOR.$assets.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
        if(!is_file($dir)){
            return $this->error('插件不存在');
        }
        $shuju = json_decode(file_get_contents($dir),true);
        if(isset($shuju['rely_on'])&&!empty($shuju['rely_on'])){
            foreach ($shuju['rely_on'] as $value){
                $value_dir = root_path().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
                if(!is_file($value_dir)){
                    return $this->error('依赖模块不存在');
                }
                $value_shuju = json_decode(file_get_contents($value_dir),true);
                if(!(isset($value_shuju['install'])&&$value_shuju['install']==1)){
                    return $this->error("{$value}模块没有安装");
                }
            }
        }
        $obj = new AssetsHand();
        $bool = $obj->installAsset($assets,$shuju,false);
        if(!$bool){
            return $this->error($obj->getMessage());
        }
        $shuju['install'] = 1;
        chmod($dir,0777);
        $str = json_encode($shuju,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
        $bool = file_put_contents($dir,$str);
        if(!$bool){
            return $this->error('修改失败');
        }
        list($bool,$error) = AssetsHand::installConfig($assets);
        if(!$bool){
            return $this->error($error);
        }
        return $this->success('安装成功');
    }
    public function delete(){
        set_time_limit(0);
        ignore_user_abort(true);
        $assets = $this->request->param('assets');
        $dir = root_path().'addons'.DIRECTORY_SEPARATOR.$assets.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
        if(!is_file($dir)){
            return $this->error('插件不存在');
        }
        $shuju = json_decode(file_get_contents($dir),true);
        if($shuju['install']==1){
            return $this->error('插件已安装，请先卸载再删除');
        }
        $bool = PublicUse::deleteDir(root_path().'addons'.DIRECTORY_SEPARATOR.$assets);
        if(!$bool){
            return $this->error('删除插件失败');
        }
        return $this->success('删除插件成功');
    }

    /**
     * 导出
     */
    public function export(){
        set_time_limit(0);
        ignore_user_abort(true);
        $assets = $this->request->param('assets');
        $data = $this->request->param();
        if(isset($data['type'])){
            if(empty($assets)){
                return $this->error('插件不存在');
            }
            $obj = new AssetsHand();
            if($data['type']==2){
                $bool = $obj->exportAsset($assets,true);
            }else{
                $bool = $obj->exportAsset($assets);
            }
            if(!$bool){
                return $this->error($obj->getMessage());
            }
            return $this->success('导出成功');
        }else{
            return Quickbuilder::makeForm()
                ->setAction()
                ->set_up_form('radio','导出类型','type',1,[1=>'导出结构',2=>'导出数据和结构'])
                ->set_button('submit','提交')
                ->fetch();
        }
    }
    public function uninstall(){
        set_time_limit(0);
        ignore_user_abort(true);
        $assets = $this->request->param('assets');
        if(empty($assets)){
            return $this->error('插件不存在');
        }
        $array = PublicUse::getdir(root_path().'addons'.DIRECTORY_SEPARATOR,[$assets,'.svn']);
        foreach ($array as $value){
            $dir = root_path().'addons'.DIRECTORY_SEPARATOR.$value.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.json';
            if(is_file($dir)){
                $shuju = json_decode(file_get_contents($dir),true);
                if(isset($shuju['rely_on'])&&$shuju['rely_on']&&is_array($shuju['rely_on'])){
                    if(in_array($assets,$shuju['rely_on'])&&(isset($shuju['install'])&&$shuju['install']==1)){
                        return $this->error('有插件依赖于本插件，请最后卸载本插件');
                    }
                }
            }
        }
        $obj = new AssetsHand();
        $bool = $obj->unInstall($assets);
        if(!$bool){
            return $this->error($obj->getMessage());
        }
        return $this->success('卸载成功');
    }
}